import { defineStore } from "pinia";
import { getStorage, setStorage, clearStorage } from "../../utils/tools";
import { store } from "../index";
import Taro from "@tarojs/taro";
import * as loginApi from "../../api/login";
import * as userApi from "../../api/user";

export const useUserStore = defineStore("user", {
  state: () => ({
    Token: getStorage(`${process.env.TOKEN}`) || "",
    Userinfo: getStorage(`${process.env.USERINFO}`) || null,
    shareUserId: 0,
  }),
  getters: {},
  actions: {
    setToken(token: string) {
      this.Token = token;
      setStorage(`${process.env.TOKEN}`, token);
    },
    setUserinfo(userinfo: object) {
      this.Userinfo = userinfo;
      setStorage(`${process.env.USERINFO}`, userinfo);
    },
    logout() {
      this.Token = "";
      this.Userinfo = "";
      clearStorage(`${process.env.TOKEN}`);
      clearStorage(`${process.env.USERINFO}`);
    },
    // 获取个人信息
    async getUserinfo() {
      const userinfoRes = await userApi.userinfo();
      this.setUserinfo(userinfoRes);
    },
    // 抖音静默登录
    async dyLogin() {
      const res = await Taro.login();
      const loginRes: any = await loginApi.dyLogin(res.code);
      this.setToken(loginRes["token"]);
      this.getUserinfo();
    },
  },
});

export function getUserStore() {
  return useUserStore(store);
}
